/*
 * @Author: yangzonglong
 * @Date: 2021-03-01 13:18:46
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: 871387321@qq.com 871387321@qq.com
 * @LastEditTime: 2023-11-15 13:11:20
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect, useCallback, useRef } from 'react';
import { Select } from '@library';
import { getTableQuery } from '../../../util';
interface RefProps {
  getData(): any;
}

const App = (props: any, ref: React.Ref<RefProps>) => {
  const { value, disabled, options, onDataLinkComBoxChange, item, scriptsChangeData } = props;

  const count = useRef(0);
  const cacheData = useRef(scriptsChangeData[options?.bindName]);

  useEffect(() => {
    setV(value || '');
  }, [value]);

  useEffect(() => {
    if (count.current === 0) {
      count.current = 1;
    } else {
      if (JSON.stringify(cacheData.current) !== JSON.stringify(scriptsChangeData[options?.bindName])) {
        cacheData.current = scriptsChangeData[options?.bindName];
        setV('');
        onDataLinkComBoxChange({}, options.extraFieldName);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [scriptsChangeData[options?.bindName], options.extraFieldName]);

  const [v, setV] = useState('');
  const [query, setQuery] = useState({});

  const onDropdownVisibleChange = useCallback((open: boolean) => {
    if (open) {
      let tableQuery = getTableQuery(options, scriptsChangeData, item);

      // 处理空where的情况，不需要传到select组件
      if(JSON.stringify(tableQuery.where) === '{}') delete tableQuery.where;
      
      setQuery(tableQuery);
    }
  }, [item, options, scriptsChangeData]);

  useImperativeHandle(ref, () => ({
    getData() {
      return v;
    },
  }));

  const placeholder = localStorage.i18nextLng === 'en' ? options?.placeholderEn : options?.placeholder;
  const url = options.serviceType === 'APP'
  ? options.modulesName && options.serviceModuleCode
    ? `/bk/api/${options.serviceModuleCode}/${options.modulesName}/find`
    : ''
  : options.modulesUrl || '';
 
  const valueKey = Array.isArray(options?.filedShowName) ? options?.filedShowName[0]?.value : options?.filedShowName;

  return (
    <div>
      <Select
        size='small'
        style={{ width: '100%' }}
        fieldNames={{ label: options?.showFieldName, value: valueKey }}
        disabled={disabled || options?.disabled}
        onDropdownVisibleChange={onDropdownVisibleChange}
        query={query}
        url={url}
        value={v}
        onChange={(e: any, record: any) => {
          if(valueKey) {
            setV(record?.[valueKey] || '');
            onDataLinkComBoxChange(record || {}, options.extraFieldName);
          }
        }}
        placeholder={placeholder}
        cacheKey={Object.keys(query).length ? undefined : url}
      ></Select>
    </div>
  );
};

export default forwardRef(App);
